/* $Id: ProblemsServlet.java 130 2011-08-26 06:58:30Z altdotua@gmail.com $ */

package alt.djudge.frontend.server.servlets;

import java.io.IOException;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import alt.djudge.frontend.server.datatypes.AbstractEntry;
import alt.djudge.frontend.server.datatypes.ProblemEntry;
import alt.djudge.frontend.server.models.CoreInterface;
import alt.djudge.frontend.server.models.ProblemsModel;


public class ProblemsServlet extends AbstractDataServlet
{

	private static final long serialVersionUID = 1L;

	@Override
	protected CoreInterface<? extends AbstractEntry> getModel()
	{
		return ProblemsModel.getCore();
	}

	@SuppressWarnings({ "rawtypes" })
	@Override
	protected void processAction(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String action = req.getParameter("action");
		if ("edit_batch".equals(action))
		{
			String sidPrefix = req.getParameter("sid_prefix");
			String sid1 = req.getParameter("sid1");
			String sidn = req.getParameter("sidn");
			String timeLimit = req.getParameter("timeLimit");
			String memoryLimit = req.getParameter("memoryLimit");
			String djudgeContest = req.getParameter("djudgeContest");
			Boolean active = req.getParameter("active") != null;
			ProblemsModel.addBatch(sidPrefix, sid1, sidn, timeLimit,
					memoryLimit, djudgeContest, active);
		}
		else if ("dump".equals(action))
		{
			Document doc = dumpData();
			OutputFormat format = OutputFormat.createPrettyPrint();
			XMLWriter writer = new XMLWriter(resp.getOutputStream(), format);
			writer.write(doc);
		}
		else if ("upload".equals(action))
		{
			System.out.println("Upload");
			try
			{
				Document doc = DocumentHelper.parseText(req.getParameter("xml"));
				Element el = doc.getRootElement();
				Iterator elementIterator = el.elementIterator();
				while (elementIterator.hasNext())
				{
					new ProblemEntry((Element)elementIterator.next()).makePersistent();
				}
			}
			catch (DocumentException e)
			{
				e.printStackTrace();
			}
		}
	}

	public static Document dumpData()
	{
		Document doc = DocumentHelper.createDocument();
		Element el = doc.addElement("Problems");

		List<ProblemEntry> list = ProblemsModel.getAllEntries();
		for (ProblemEntry problemEntry : list)
			el.add(problemEntry.getXml().getRootElement());

		return doc;
	}

	@Override
	protected boolean processEdit(HttpServletRequest req,
			HttpServletResponse resp)
	{
		return true;
	}
}
